<?php

namespace app\dao\shop;

use app\dao\BaseDao;
use app\model\Shop;
use app\model\ShopFreight;
use think\facade\Db;

class FreightDao extends BaseDao
{

    public function create(array $data)
    {
        return $this->save([
            'name' => $data['name'],
            'type' => $data['type'],
            'min_amount' => $data['min_amount'] * 100,
            'per_amount' => $data['per_amount'] * 100,
            'min_unit' => $data['min_unit'],
            'per_unit' => $data['per_unit'],
            'shop_id' => $data['shop_id'],
            'status' => 0,
        ]);
    }

    public function getListByShopId($shop_id, $page, $perPage)
    {
        $query = $this->getModel()->where('shop_id', '=', $shop_id)->with(['special'=>function($query){
            return $query->filter(function($query) {
                $query->min_amount  = $query->min_amount / 100;
                $query->per_amount  = $query->per_amount / 100;
            });
        }])->filter(function($query) {
            $query->min_amount  = $query->min_amount / 100;
            $query->per_amount  = $query->per_amount / 100;
        });

        return $this->pagination($query, $page, $perPage);
    }

    public function getById($id)
    {
        return $this->getModel()->with(['special'=>function($query){
            return $query->filter(function($query) {
                $query->min_amount  = $query->min_amount / 100;
                $query->per_amount  = $query->per_amount / 100;
            });
        }])->filter(function($query) {
            $query->min_amount  = $query->min_amount / 100;
            $query->per_amount  = $query->per_amount / 100;
        })->find($id);
    }

    public function updateById(array $data, $id)
    {
        $data['min_amount'] = $data['min_amount'] * 100;
        $data['per_amount'] = $data['per_amount'] * 100;
        $this->update($data, $id);

        return $this->getById($id);
    }

    public function getAll($shop_id)
    {
        $query = $this->getModel()->where('shop_id', '=', $shop_id)->with(['special'=>function($query){
            return $query->filter(function($query) {
                $query->min_amount  = $query->min_amount / 100;
                $query->per_amount  = $query->per_amount / 100;
            });
        }])->filter(function($query) {
            $query->min_amount  = $query->min_amount / 100;
            $query->per_amount  = $query->per_amount / 100;
        });
        return [
            'pagination' => ['page' => 1, 'perPage' => -1, 'total' => $query->count()],
            'list'       => $query->select()
        ];
    }

    protected function setModel(): string
    {
        return ShopFreight::class;
    }

    public function deleteById($id)
    {
        $this->getModel()->destroy($id);
    }

}